const Service = require('egg').Service;
module.exports = app => {
  return class OperationLogService extends Service {
    async list(pageNo = 1, pageSize = app.config.pageBean.pageSize, where = {}) {
      const app = this.app;
      const ctx = this.ctx;
      let options = {
        where: where,
        offset: (+pageNo - 1) * +pageSize,
        limit: +pageSize,
        order: [['update_time', 'DESC']],
        include: [{
          model: ctx.model.User,
          as: 'user',
          attributes: ['id', 'avatar', 'user_id', 'real_name', 'org_node_name']
        }],
        distinct: true
      };
      return await ctx.model.OperationLog.findAndCountAll(options);
    }

    /**
     * @description 获取最新操作记录条数的
     * @author xiezuobing[948466]<435321508@qq.com>
     * @param {number} [pre=20] 
     * @returns  
     * @memberof OperationLogService
     */
    async getPreList(targetType, type, targetId, pre = 20) {
      const ctx = this.ctx;
      return await ctx.model.OperationLog.findAll({
          where: {
            type: type,
            target_type: targetType,
            target_id: targetId
          },
          offset: 0,
          limit: pre,
          order: [['update_time', 'DESC']],
          include: [
            {
              model: ctx.model.User,
              as: 'user',
              attributes: ['id', 'avatar', 'user_id', 'real_name']
            }
          ]
        });
    }

    /**
     * @description 创建
     * @author xiezuobing[948466]<435321508@qq.com>
     * @param {any} type 
     * @param {any} targetType 
     * @param {any} targetId 
     * @returns  
     * @memberof OperationLogService
     */
    async create(type, targetType, targetId, userId) {
      const ctx = this.ctx;
      const log = await ctx.model.OperationLog.findOne({
        where: {
          type: type,
          target_type: targetType,
          target_id: targetId,
          user_id: userId
        }
      })
      if (log) {
        return await log.update({
            update_time: new Date(),
            times: app.Sequelize.literal('`times` +1'),
          });
      } else {
        return await ctx.model.OperationLog.create({
            create_time: new Date(),
            update_time: new Date(),
            user_id: ctx.session.frontUser.user_id,
            type: type,
            target_type: targetType,
            target_id: targetId,
            times: 1,
          })
      }
    }
  }
}